<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="dialogVisible" title="选择文件上传方式" width="800" :before-close="closeDialog">
    <el-radio-group v-model="radioSelect" class="pb-2 pl-3">
      <el-radio value="1">选择本地文件</el-radio>
      <el-radio value="2">选择系统文件</el-radio>
    </el-radio-group>
    <el-upload
      v-if="radioSelect === '1'"
      v-model:file-list="fileList"
      action="#"
      :auto-upload="false"
      multiple
      :limit="limit"
      class="pl-3"
      :on-exceed="handleExceed"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传{{ accept }}格式文件</div>
      </template>
    </el-upload>
    <div v-else>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small">
        <el-form-item label="源文件名称" prop="name" label-width="90">
          <el-input v-model="queryParams.name" placeholder="请输入源文件名称" clearable style="width: 120px" />
        </el-form-item>
        <el-form-item label="文件格式" prop="extension" label-width="90">
          <el-select v-model="queryParams.extension" placeholder="请选择" clearable style="width: 120px">
            <el-option v-for="dict in inputModelTypes" :key="dict.value" :label="dict" :value="dict" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="tableDatas" row-key="id" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="序号" type="index" width="80" :index="indexMethod" />
        <el-table-column label="源文件名称" prop="name" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="文件格式" prop="extension" width="150" />
        <el-table-column label="文件类型" prop="type" width="150" />
        <el-table-column label="文件大小" prop="size" width="120">
          <template #default="scope">
            {{ getSizeStr(scope.row.size) }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <template #footer>
      <div class="dialog-footer text-center">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="sureDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="UploadFileDialog" lang="ts">
import type { UploadProps } from 'element-plus';
import { types } from '@/api/caxDataConversionMajorComponent/index';
import { sourceFileList } from '@/api/caxDataConversionMajorComponent/fileManagement/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const prop = defineProps({
  limit: {
    type: Number,
    default: 5
  },
  accept: {
    type: String,
    default: ''
  }
});
const queryParams = reactive({
  name: '',
  extension: '',
  type: '',
  pageNum: 1,
  pageSize: 10
});
const fileList = ref([]);
const total = ref(0);
const loading = ref(false);
const tableDatas = ref([]);
const multipleSelection = ref([]);
const fileTypes = ref(types);
const queryFormRef = ref<ElFormInstance>();
const inputModelTypes = ref([]);
const emit = defineEmits(['on-sure', 'on-sure2']);
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`当前限制${prop.limit}, 你选择了这次选择了 ${files.length} 个文件, 共选择了${files.length + uploadFiles.length}文件`);
};
const handleTypeChange = () => {
  if (queryParams.type) {
    const obj = fileTypes.value.find((item) => item.value === queryParams.type);
    if (obj) {
      inputModelTypes.value = obj.inputType;
      return;
    }
  }
  let arr = [];
  fileTypes.value.forEach((element) => {
    arr = [...arr, ...element.inputType];
  });
  inputModelTypes.value = arr;
};
const getSizeStr = (size) => {
  if (size < 1024) {
    return size + 'B';
  } else if (size > 1023 && size < 1024 * 1024) {
    return Number(size / 1024).toFixed(2) + 'kB';
  } else {
    return Number(size / 1024 / 1024).toFixed(2) + 'MB';
  }
};
const indexMethod = (index) => {
  return (queryParams.pageNum - 1) * queryParams.pageSize + index + 1;
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const checkFile = () => {
  if (!fileList.value.length) {
    proxy?.$modal.msgError(`请选择上传的文件`);
    return false;
  }
  for (let i = 0; i < fileList.value.length; i++) {
    const name = fileList.value[0].name;
    const type = name.substring(name.lastIndexOf('.')).toLocaleLowerCase();
    if (!prop.accept.includes(type)) {
      proxy?.$modal.msgError(`限制文件上传${prop.accept}类型文件`);
      return false;
    }
  }
  return true;
};
/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const dialogVisible = ref(false);
const radioSelect = ref('1');
const openDialog = () => {
  fileList.value = [];
  multipleSelection.value = [];
  radioSelect.value = '1';
  getList();
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
const getList = async () => {
  loading.value = true;
  const res = await sourceFileList(queryParams);
  tableDatas.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const sureDialog1 = () => {
  if (!checkFile()) {
    return;
  }
  emit('on-sure', fileList.value);
  closeDialog();
};
const sureDialog2 = () => {
  if (!multipleSelection.value.length) {
    proxy?.$modal.msgError(`请选择上传的文件`);
    return false;
  }
  if (multipleSelection.value.length > prop.limit) {
    proxy?.$modal.msgError(`限制上传${prop.limit}个文件，请重新选择文件`);
    return false;
  }
  const str = prop.accept.toLocaleLowerCase();
  const obj = multipleSelection.value.filter((item) => !str.includes(item.extension.toLocaleLowerCase()));
  if (obj.length) {
    proxy?.$modal.msgError(`限制文件上传${prop.accept}类型文件`);
    return false;
  }
  emit('on-sure2', multipleSelection.value);
  closeDialog();
};
const sureDialog = () => {
  if (radioSelect.value === '1') {
    sureDialog1();
  } else {
    sureDialog2();
  }
};
onMounted(() => {
  handleTypeChange();
});
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped></style>
